﻿using System;
using System.Xml;
using System.Xml.XPath;

[assembly: System.CLSCompliant(true)]
namespace Netfraction.Common.DataStorage
{
    public class DataSource
    {
        private static XmlDataStore _sourceStore;

        public string Name { get; set; }
        public Guid Guid { get; set; } // can generate with GuidGen from Windows SDK, via C# code, or at http://www.guidgen.com/
        public string Version { get; set; }
        public string Author { get; set; }
        public string SiteUrl { get; set; }
        public string UpdateUrl { get; set; }
        public string SourceLicence { get; set; }

        private static bool CheckStoreExists()
        {
            _sourceStore = new XmlDataStore(StorageDataSource.DataSource, "DataSources.xml");

            if (_sourceStore == null)
                return false;

            if (_sourceStore.IsEmpty())
            {
                XmlTextWriter xWriter = _sourceStore.CreateWriter();
                xWriter.Formatting = Formatting.Indented;

                xWriter.WriteStartDocument();
                xWriter.WriteStartElement("DataSources");
                xWriter.WriteEndElement();
                xWriter.WriteEndDocument();

                xWriter.Flush();
                xWriter.Close();
            }
            return true;
        }

        public static bool RegisterSource(DataSource source)
        {
            if (!CheckStoreExists())
                return false;
                        
            XPathNavigator xNav = _sourceStore.CreateNavigator(true);
            XPathNodeIterator xIter = xNav.Select("//DataSources/Source[@guid=\"" + source.Guid.ToString() + "\"]");
            if (xIter.Count > 0)
                return false;   // source already exists

            if (!xNav.CanEdit)
                return false;

            xNav.MoveToChild("DataSources", "");

            using (XmlWriter xWriter = xNav.AppendChild())
            {
                xWriter.WriteStartElement("Source");
                xWriter.WriteAttributeString("guid", source.Guid.ToString());
                xWriter.WriteElementString("Name", source.Name);
                xWriter.WriteElementString("Version", source.Version);
                xWriter.WriteElementString("Author", source.Author);
                xWriter.WriteElementString("SiteUrl", source.SiteUrl);
                xWriter.WriteElementString("UpdateUrl", source.UpdateUrl);
                xWriter.WriteElementString("SourceLicence", source.SourceLicence);
                xWriter.WriteEndElement();
            }
            return _sourceStore.Save();
        }
    }
}